var appPath = getAppPath();
var uploader = null;

$(function(){
	
	// 大分类
	$("#queryTmplType").combobox({
		url:appPath+'/itbTg/getTypeForCombo.action?topIds=1,2,3,4,6,7,8,1010,1011,1030&blkFlg=1',
		valueField:'type_id',
		textField:'type_name',
		onSelect:function(selRecd){
			$("#queryTmplType2").combobox("clear");
			$("#queryTmplType3").combobox("clear");
			$("#queryTmplType2").combobox("loadData",{});
			$("#queryTmplType3").combobox("loadData",{});
			
			// 中分类
			var parentId=selRecd.type_id;
			if(Number(parentId)>0){
				$("#queryTmplType2").combobox({
					url:appPath+'/itbTg/getTypeForCombo.action?parent='+parentId+'&blkFlg=1',
					valueField:'type_id',
					textField:'type_name',
					onSelect:function(selRecd2){
						$("#queryTmplType3").combobox("clear");
						$("#queryTmplType3").combobox("loadData",{});
						
						// 小分类
						var parentId2=selRecd2.type_id;
						if(Number(parentId2)>0){
							$("#queryTmplType3").combobox({
								url:appPath+'/itbTg/getTypeForCombo.action?parent='+parentId2+'&blkFlg=1',
								valueField:'type_id',
								textField:'type_name',
								onSelect:function(selRecd3){
									// TODO
								}
							});
						}
					}
				});
			}
		}
	});
	
	// 组织
	$("#queryTgOrg").combobox({
		url:appPath+'/itbDesign/getOrgInfoLst.action',
		valueField:'org_id',
		textField:'name',
		onLoadSuccess:function(){
			var data = $('#queryTgOrg').combobox('getData');
			 $("#queryTgOrg").combobox('select',data[0].org_id);
			 
			 // 加载并选定一个组织后再检索
			 initJspGrid();
		},
		onSelect:function(selRecd){
			// TODO
		}
	});
	
	initJspGrid();
	initSaleGrid();
});

// 获取分类信息
function getTopTypeNm(value){
	var tn = '';
	switch(Number(value||'0')){
  	case 1: tn='单页';break;
  	case 2: tn='多页';break;
  	case 3: tn='PPT';break;
  	case 4: tn='<span style="color:red">印品</span>';break;
  	case 6: tn='社交媒体';break;
  	case 7: tn='电商';break;
  	case 8: tn='微商';break;
  	case 1010: tn='Logo商品';break;
  	case 1011: tn='营销商品';break;
  	case 1030: tn='视频背景';break;
  }
  return tn;
}

// 设计模版列表初始化
function initJspGrid(){
	
	$('#tmplGrid').datagrid({
	    url:appPath + "/itbDesign/getDesignInfoLst.action",
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    nowrap: false,// 换行
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'thumb',title:'缩略图',width:70,align:'left',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
					if (thumb) {
						retUrl = '<a href="' + thumb + '" target="_blank">'
							+ '<div style="display:table;text-align:center;height:110px;width:100%">'
							+ '<span style="display:table-cell;vertical-align:middle">'
							+ '<img src="' +thumb+'?x-oss-process=image/resize,m_lfit,h_120,w_100'
							+ '" style="display:inline;max-height:100px;max-width:100px"></span></div></a>';
					}
					return retUrl;
	        	}
  	        },
//			{field:'editTmpl',title:'编辑',width:25,align:'center',sortable:false,
//				formatter:function(value,rowData,rowIndex){
//					//if(!rowData.map_id) return "";
//					var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' ";
//					ret += " onClick='editTmpl("+rowData.design_id+","+rowData.type_id+","+rowData.publish+")'/></a>";
//					return ret;
//				}
//			},
	        {field:'design_id',title:'模板ID',width:45,align:'center',sortable:false,
		    	formatter:function(id, rowData, rowIndex){
		    		var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' ";
					ret += " onClick='editTmpl("+rowData.design_id+","+rowData.type_id+","+rowData.publish+")'/></a>";
		    		var show = '<font color="#8B0A50">u:'+rowData.uni_item_id+'</font>'+
		    		  	'</br>'+
		    		  	'<font color="red">d:'+id+'</font>'+
		    		  	'</br>'+
		    		  	'<span style="color:#8B5742;">m:'+rowData.map_id+'</span>'+
		    		  	'<br/>'+ret;
		    		return show;
		    	}
		    },
//	        {field:'map_id',title:'分页ID',width:30,align:'left',sortable:false,
//		    	  formatter:function(mapId, rowData, rowIndex){
//		    		  return '<span style="color:green">'+mapId+'</span>';
//		    	  }
//		      },
	        {field:'size',title:'尺寸',width:45,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		return 'w:'+(rowData.width||'N/A')+
		    			'</br><span style="color:#363636;">*</span></br>h:'+
		    			(rowData.height||'N/A')+'';
		    	}
		    },
		    {field:'top_type',title:'分类',width:40,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var tn = getTopTypeNm(value);
		    		if(!tn || tn.length==0) {
		    			tn = '<span style="color:red">未知</span>';
		    		}
		    		return '<font color="#473C8B">'+tn+'</font>' +'<br/>*<br/>'+'<font color="red">'+rowData.type_name+'</font>';
		    	}
		    },
//	        {field:'editType',title:'子分类',width:40,align:'center',sortable:false,
//		    	formatter:function(value, rowData, rowIndex){
//		    		return rowData.type_name || '<span style="color:red">未分类</span>';
//		    	}
//		    },
		    {field:'user_id',title:'设计师',width:50,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		return rowData.nickname || rowData.user_name || rowData.user_id || '<span style="color:red">未知</span>';
		    	}
		    },
			{field:'src_url',title:'源文件',width:30,align:'center',sortable:false,
				formatter:function(value,rowData,rowIndex){
					if(rowData.top_type!=1010) {// 暂时仅限logo
						return "<span style='color:#8B4C39;'>N/A</span>";
					}
					
					var show = '上传';
					if(rowData.src_url && rowData.src_url.length>0) {
						show = '修改';
					}
		    		return "<a href='javascript:void(0)' onClick='showSrcUploadDlg("+rowData.design_id+",\""+(rowData.src_url||'')+"\")'>"+show+"</a>";
		    	}
			},
		    {field:'item_id',title:'关联商品',width:40,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var topType = Number(rowData.top_type||'0');
		    		if(topType!=4 && topType!=1010 && topType!=1011) {
		    			return "<span style='color:#8B4C39;'>N/A</span>";
		    		}
		    		if(Number(value||'0')==0) {
		    			return '<span style="color:#8B4C39">无</span>';
		    		}
		    		return value;
		    	}
		    },
		    {field:'keyword',title:'关键词',width:35,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		if(!rowData.design_id) return "";
		    		var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='设置' ";
					ret += " onClick='editKeyword("+rowData.design_id+","+(rowData.top_type||0)+")'/></a>";
					return ret;
		    	}
		    },
		    {field:'vSize',title:'占位图',width:30,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		if(rowData.top_type != 1030) return "<span style='color:#8B4C39;'>N/A</span>";
		    		var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/undo.png' title='设置' ";
					ret += " onClick='ShowViSize("+rowData.video_size_id+","+JSON.stringify(rowData.video_pos).replace(/"/g, '&quot;')+")'/></a>";
					return ret; 
		    	}
		    },
	        {field:'order',title:'排序',width:35,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.design_id) return "";
		    		  return "<a href='javascript:void(0)' onClick='editOrder("+rowData.design_id+","+rowData.order+")'>"+rowData.order+"</a>";
		    	  }
		    },
	        {field:'design_name',title:'设计模版名称',width:85,align:'left',sortable:false},
	        {field:'price',title:'设计费',width:42,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.design_id || Number(rowData.top_type||'0')!=4) return "<span style='color:#8B4C39;'>N/A</span>";
		    		  return "<a href='javascript:void(0)' onClick='editPrice("+rowData.design_id+","+rowData.price+")'>"+(rowData.price/100)+"元</a>";
		    	  }
		      },
	        {field:'sale',title:'售价',width:30,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.design_id || Number(rowData.top_type||'0')==4) return "<span style='color:#8B4C39;'>N/A</span>";
		    		  var show = '免费';
		    		  if(Number(rowData.tmpl_price_cnt||'0')>0) {
		    			  show = '付费('+rowData.tmpl_price_cnt+')';
		    		  }
		    		  return "<a href='javascript:void(0)' onClick='showSaleList("+rowData.design_id+","+rowData.top_type+")'>"+show+"</a>";
		    	  }
		      },
	        {field:'vip',title:'VIP',width:30,align:'center',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  var show = '普通';
		    		  if(Number(value||'0')==10) show="<span style='color:red;'>VIP</span>";
		    		  return "<a href='javascript:void(0)' onClick='editVip("+rowData.design_id+","+rowData.vip+")'>"+show+"</a>";
		    	  }
		    },
//		    {field:'topic',title:'专题',width:30,align:'center',sortable:false,
//		    	  formatter:function(value, rowData, rowIndex){
//		    		  if(!rowData.design_id) return "";
//		    		  var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='设置' ";
//					  ret += " onClick='editTopic("+rowData.design_id+","+(rowData.type_id||0)+","+(rowData.parent_type||0)+","+(rowData.top_type||0)+")'/></a>";
//					  return ret;
//		    	  }
//		      },
        	{field:'state',title:'模版状态',width:45,align:'center',sortable:false,
	        	formatter:function(state, rowData, rowIndex){
	        		var st = '';
	        		var state2 = rowData.state2;
	        		if (Number(rowData.state2)>0 && rowData.state2!=32){// 
	        			console.log(state2);
	        			st = '<br/>#<br/><font color="red">下架申请中</font>';
	        		} else if (rowData.state2 == 32){
	        			st = '<br/>#<br/><font color="green">下架复审通过</font>';
	        		}
	        		var s = Number(state||'0');
	        		var nm = '未知';
	        		switch(s){
	        			case 10: nm='<font color="#CD3700">制作中</font>';break;
	        			case 20: nm='<span style="color:blue">待审核</span>'+st+'';break;
	        			case 31: nm='<span style="color:orange">初审OK</span>'+st+'';break;
	        			case 41: nm='<span style="color:red">初审NG</span>'+st+'';break;
	        			case 32: nm='<span style="color:green">复审OK</span>'+st+'';break;
	        			case 42: nm='<span style="color:red">复审NG</span>'+st+'';break;
	        		}
	        		return nm;
	        	}
		    },
	        {field:'publish',title:'发布状态',width:45,align:'center',sortable:false,
	        	formatter:function(publish, rowData, rowIndex){
	        		if (Number(publish) == 1) return '<span style="color:green">已发布</span>';
	        		return '<span style="color:red">未发布</span>';
	        	}
	        },
	        {field:'shApply',title:'用户作品',width:35,align:'center',sortable:false,
	        	formatter:function(publish, rowData, rowIndex){
	        		var dcnt = Number(rowData.dcnt||'0');
	        		return '<a href="javascript:void(0)" onclick="shApply('+rowData.design_id+')">['+dcnt+']</a>';
	        	}
	        },
	        {field:'meal',title:'<span style="color:red;">一键秀</span>',width:30,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
//		    		return "<a href='javascript:void(0)' onclick='showPrice("+rowData.design_id+")'>设定</a>";
		    		return "<a href='javascript:void(0)' onclick='setYjxInfo("+rowData.uni_item_id+","+rowData.design_id+","+rowData.form_id+")'>设定</a>";
		    	}
		    },
	        {field:'create_time',title:'创建时间',width:50,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:50,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'发布设计模版',
			iconCls:'icon-ok',
			handler:function(){
				doPublish();
			}
		},
		{
			text:'取消发布',
			iconCls:'icon-cancel',
			handler:function(){
				cancelPublish();
			}
		},
		{
			text:'删除设计模版',
			iconCls:'icon-no',
			handler:function(){
				delTmpl();
			}
		}]
	    
	});
}


// 设置相关参数
function setYjxInfo(uitemId,id,formId){
	$("#yjxDesignId").val(id);
	$("#yjxUnitemId").val(uitemId);
	$("#yjxFormId").val(formId);
	
	$('#yjxSetDlg').window({
		title:'一键秀模板相关参数设置页面',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#yjxSetDlg').window('move',{top:20,left:20});
	$('#yjxSetDlg').window('open');
}

//展示价格套餐
function showPrice(){
	var design_id = $("#yjxDesignId").val();
	$("#tgDesignId").val(design_id);// 模板ID
	$('#mealTable').html('');
	if (design_id==null || design_id.length<=0){
		$.messager.alert('提示信息','该模板不能设定套餐信息！请联系管理员','warning');
		return;
	}
	
	var url = appPath+"/itbDesign/getYjxTgPriceMealInfo.action?tgDesignId="+design_id;
	$.post(url,function(ret){	
		if(ret && ret.length>0){
			for(var i=0; i<ret.length; i++){
				var sub = ret[i];
				if(sub && sub.length>0){
					$("#uItemId").val(sub[0].uni_item_id);
					var itemHtml = '<tr><td class="queryTitle" width="100px">'+sub[0].type_name+'套餐</td>'+
							'<td class="queryContent" colspan="4">';
					for(var n=0; n<sub.length; n++){
						var chk = (Number(sub[n].isChk||'0')>0)?"checked":"";
						itemHtml += '<div style="width:80px;float:left">'+
							'<input type="checkbox" '+chk+' id="price_'+sub[n].price_id+'" name="viPriceInfo" value="'+sub[n].price_id+'"/>'+
							sub[n].name+'</div>';
					}
					itemHtml += '</td></tr>';
					$('#mealTable').append(itemHtml);
				}
			}
		}
	});
	
	$("#mealBtn").show();
	$('#mealDlg').window({
		title:'视频模板套餐价格',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#mealDlg').window('move',{top:20,left:20});
	$('#mealDlg').window('open');
}

function cancelMeal(){
	$('#mealDlg').window('close');
}

/* 设计一键秀 模板套餐价格
 */
function updMeal(){
	var priceId = $("input[name='viPriceInfo']:checked").map(function(){
        	return $(this).val();
        }).get(); //  获取priceId
	var uItemId = $("#uItemId").val();// 模板统一ID
	$.messager.confirm("确认", "是否设置更新套餐？", function (r) {
		if(r){
			var url = appPath +"/itbDesignWeb/addPriceRInfo.action";
			var data = {
					'uItemId':uItemId,
					'price_id':priceId.join(',')
			};
			$.post(url,data,function(ret){
				if(ret == 'ok'){
					$.messager.alert('提示信息','设置套餐成功','info');
				}else{
					$.messager.alert('提示信息','设置套餐失败','warning');
				}
			});
		}
	});
	
}

/* View the template user application list
 */
function shApply(id){
	$("#udocForm").form('clear');
	$("#uDocTable").show();
	$("#disign_id").html(id);
	$("#uDocDlg").window({
		title :'显示用户文档信息',
		iconCls :'icon-blank',
		modal :true,
		shadow :true,
		collapsible :false,
		minimizable :false,
		maximizable :false
	});
	$('#uDocDlg').window('move',{top:20,left:20});
	$('#uDocDlg').window('open');
	initUserdocGrid(id);
}

/**Initializes the load user document information
 */
function initUserdocGrid(id){
	$('#uDocGrid').datagrid({
	    url:appPath + "/itbDesign/getDisUserDocInfo.action?disId="+id,
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam3(),
	    singleSelect:true,
	    selectOnCheck:true,
	    checkOnSelect:true,
	    columns:[[
			{field : 'thumb',title : '缩略图',width : 30,align : 'center',sortable : false,
				formatter : function(value, rowData, rowIndex) {
					var retUrl = '';
					if (value) {
						retUrl = '<a href="' +value+ '" target="_blank">'
							+ '<div style="display:table;text-align:center;height:70px;width:70px;">'
							+ '<span align="center" style="display:table-cell;vertical-align:middle">'
							+ '<img src="'+value+'?x-oss-process=image/resize,m_lfit,h_100,w_100'
							+ '" style="display:inline;max-height:60px;max-width:60px;"/></span></div></a>';
					}
					return retUrl;
				}
			},
			{field:'doc_id',title:'用户作品ID',width:30,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var show = value;
	        		if (Number(value||'0')>0) {
	        			var url = getHomeServer()+'/preview/pDocV?docId='+value;
	        			show = '<a href="' + url + '" target="_blank">'+value+'</a>';
	        		}
	        		return show;
	        	}
	        },
	        {field:'doc_name',title:'文档名称',width:55,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		if(value){
  	        			return '<span style="color:	#555555;">'+value+'</span>';
  	        		}
	        		return '<span style="color:#B0B0B0;">暂无</span>';
	        	}
		    },
	        {field:'purpose',title:'文档分类',width:30,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		var tem = '';
  	        		switch(Number(value||'0')){
	  	        		case 0: tem ='<span style="color:green;">普通文档</span>'; break;
	  	        		case 1: tem ='<span style="color:#FFBBFF;">测试用</span>'; break;
	  	        		case 2: tem ='<span style="color:blue;">印品订单</span>'; break;
  	        		}
  	        		return tem;
	        	}
		    },
		    {field :'user_id',title :'用户ID', width:25, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if(value){
		    			return '<span style="color:#555555;">'+value+'</span>';
		    		}
		    	}
		    },
		    {field :'nickname',title :'用户昵称', width:35, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		if(value){
		    			return '<span style="color:#436EEE;">'+value+'</span>';
		    		}
		    		return '<span style="color:red;">无名用户</span>';
		    	}
		    },
		    {field :'mobile',title :'手机号', width:30, align:'center',sortable:false,
		    	formatter:function(value,rowData,rowIndex){
		    		return value || '<span style="color:#9C9C9C">暂未填写</span>';
		    	}
		    },
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	});
}

// 售价条目
function initSaleGrid(){
	$('#saleGrid').datagrid({
	    url:appPath + "/itbDesign/getTmplPriceInfoLst.action",
	    height:'360',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam2(),
	    singleSelect:true,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'price_id',title:'价目ID',width:35,align:'left',sortable:false},
	        //{field:'type',title:'模版类型',width:40,align:'left',sortable:false},
	        //{field:'tmpl_id',title:'模版ID',width:40,align:'left',sortable:false },
	        {field:'price',title:'售价',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.price_id || !rowData.tmpl_id) return '<span style="color:red;">N/A</span>';
	        		return (Number(value||'0')/100)+'元';
	        	}
		    },
	        {field:'period',title:'有效时长',width:50,align:'right',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
  	        		return Number(value||'0')+'天';
	        	}
		    },
	        {field:'free',title:'限时免费',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.price_id || !rowData.tmpl_id) return '<span style="color:red;">N/A</span>';
	        		var show = (Number(value||'0')==1)?'<span style="color:red;">YES</span>':'NO';
	        		return "<a href='javascript:void(0)' onClick='editFree("+rowData.price_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:40,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[]
	});
}

/**
 * 编辑设计模版
 */
function editTmpl(designId, typeId, publish){
	if (publish == 1 || publish =="1") {
		$.messager.alert('提示信息','请勿编辑已发布设计模版！','warning');
	} else {
		// 非加密方式
		//var editorUrl = getDesignServer()+"/design/getWorkEditors?"+"uId="+g_userId+"&dId="+designId;
		// 加密方式
		var editorUrl = getDesignServer()+'/encrypt/encrypt'
			+urlWithPara({'uId':g_userId,'dId':designId,'typeId':typeId,'destination':'/playFormgoods/v1_0_designEdit'});
		window.open(editorUrl);
	}
}

/**
 * 删除设计模版
 */
function delTmpl(){
	var selectItem=$("#tmplGrid").datagrid("getChecked");
	var ids = "";// 删除的模板ID
	var publish = '';// 模板发布状态
	var cnt = 0;
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择设计模版','warning');
		return;
	} else {
		$.each(selectItem, function(index, item){
			ids = ids + item.design_id + ",";
			publish = Number(publish)+Number(item.publish);
			cnt++;
		});
		console.log(publish);
		if (publish >= 1){
			$.messager.alert('提示信息','不能选择已发布的模板 进行删除!','warning');
			return;
		}
//		if (cnt>1) {
//			$.messager.alert('提示信息','请单选删除','warning');
//			return;
//		} else {
//		}
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var url = appPath+"/itbDesignWeb/deleteDesign.action?ids="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery();
				}else{
					$.messager.alert('提示信息','删除失败','info');
				}
			});
        }
	});
}

/**
 * 显示顺序
 */
function editOrder(designId, order){
	$("#designId").val(designId);
	$("#order").val(order);
	
	$("#orderBtn").show();
	$('#orderDlg').window({
		title:'显示顺序设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#orderDlg').window('move',{top:20,left:20});
	$('#orderDlg').window('open');
}
/**
 * 修改显示顺序
 */
function doUpdOrder(){
	var designId = $("#designId").val();
	var order = $("#order").val();
	if(!order || order.length == 0 || Number(order)>999 || Number(order)<=0){
		$.messager.alert('提示信息','有效数值范围为：1～999','warning');
		return;
	}
	
	var url = appPath+"/itbDesignWeb/updDesignOrder.action?designId="+designId+"&order="+order;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','显示顺序已更新！','info',function(){
				doQuery();
				$('#orderDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','显示顺序更新失败！','warning');
		}
	});
}
/**
 * 结束显示顺序编辑
 */
function cancelUpdOrder(){
	$('#orderDlg').window('close');
}

/**
 * 印品设计费
 */
function editPrice(designId, price){
	$("#pDId").val(designId);
	$("#updPrice").val(price);
	
	$("#priceBtn").show();
	$('#priceDlg').window({
		title:'设计费设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#priceDlg').window('move',{top:20,left:20});
	$('#priceDlg').window('open');
}
/**
 * 修改设计费
 */
function doUpdPrice(){
	var designId = $("#pDId").val();
	var price = Number($("#updPrice").val()||'0');
	if(isNaN(price) || price<0){
		$.messager.alert('提示信息','请输入有效数值','warning');
		return;
	}
	
	var url = appPath+"/itbDesignWeb/updDesignPrice.action?designId="+designId+"&price="+price;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','设计费已更新！','info',function(){
				doQuery();
				$('#priceDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','设计费更新失败！','warning');
		}
	});
}
/**
 * 结束设计费编辑
 */
function cancelUpdPrice(){
	$('#priceDlg').window('close');
}

/**
 * 模版价目表
 */
function showSaleList(designId,topType){
	$("#sDId").val(designId).html(designId);
	var tn = getTopTypeNm(topType) || '未知';
	$("#sTopType").val(topType).html(tn);
	doQuery2();
	
	$("#saleBtn").show();
	$('#saleListDlg').window({
		title:'模版价目表',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#saleListDlg').window('move',{top:20,left:20});
	$('#saleListDlg').window('open');
}
function closeSaleList(){
	$('#saleListDlg').window('close');
}

// 添加价格条目
function addSale(){
	$('#saleEditForm').form('clear');
	
	var dId = Number($("#sDId").val()||'0');
	var tt = Number($("#sTopType").val()||'0');
	var tn = getTopTypeNm(tt) || '未知';
	$("#sEdtDId").val(dId).html(dId);
	$("#sEdtType").val(tt).html(tn);
	
	$("#saleEditBtn").show();
	$('#saleEditDlg').window({
		title:'模版售价设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#saleEditDlg').window('move',{top:20,left:20});
	$('#saleEditDlg').window('open');
}
function doSaleEdit(){
	var dId = Number($("#sEdtDId").val() || '0');
	var type = Number($("#sEdtType").val() || '0');
	var price = Number($("#sEdtPrice").val() || '0');
	var period = Number($("#sEdtPeriod").val() || '0');
	if(isNaN(price) || price==0 || isNaN(period) || period==0) {
		$.messager.alert('提示信息','请填写正确的售价及有效时长！','warning');
		return;
	}
	
	var url = appPath+"/itbDesignWeb/addTmplPrice.action"
	var sendData = {
		"tmplPriceInfo.type": type,
		"tmplPriceInfo.tmpl_id": dId,
		"tmplPriceInfo.price": price,
		"tmplPriceInfo.period": period
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','提交成功','info');
			$('#saleEditDlg').window('close');
			doQuery2();
        } else {
        	$.messager.alert('提示信息','提交失败','info');
        }
    });
}
function cancelSaleEdit(){
	$('#saleEditDlg').window('close');
}
// 删除价格条目
function delSale(){
	var selectItem=$("#saleGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择价格条目','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.price_id + ",";
			});
			var url = appPath+"/itbDesignWeb/delTmplPrice.action?ids="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery2();
				}else{
					$.messager.alert('提示信息','删除失败','info');
				}
			});
        }
	});
}

// 设定vip模版
function editVip(designId, vip){
	$("#vDId").val(designId);
	$("#updVip").combobox('select',Number(vip||'0')||0);
	
	$("#vipBtn").show();
	$('#vipDlg').window({
		title:'VIP模版设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#vipDlg').window('move',{top:20,left:20});
	$('#vipDlg').window('open');
}
function doUpdVip(){
	var designId = $("#vDId").val();
	var vip = $("#updVip").combobox('getValue');
	if((Number(designId||'0')||0) <= 0) {
		$.messager.alert('提示信息','无效设计模版ID!','warning');
		return;
	}
	
	var url = appPath+"/itbDesignWeb/updDesignVip.action?designId="+designId+"&vip="+vip;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','vip属性已更新！','info',function(){
				doQuery();
				$('#vipDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','vip属性更新失败！','warning');
		}
	});
}
function cancelUpdVip(){
	$('#vipDlg').window('close');
}


// 设置限免
function editFree(){
	// TODO
}

/**
 * 发布
 */
function doPublish(){
	var selectTmpl=$("#tmplGrid").datagrid("getChecked");
	if(!selectTmpl || selectTmpl.length == 0){
		$.messager.alert('提示信息','请选择未发布设计模版进行处理！','warning');
		return;
	}else if(selectTmpl.length>1){
		$.messager.alert('提示信息','请选择单个设计模版进行处理！','warning');
		return;
	}
	
	var ids = "";
	var doFlg = false;
	$.each(selectTmpl, function(index, item){
		if(item.publish != 1 && item.publish != '1' && !doFlg){
			doFlg = true;
			//ids = ids + item.design_id + ",";
			ids = item.design_id;
		}
	});
	
	if(!doFlg){
		$.messager.alert('提示信息','请选择未发布设计模版进行处理！','warning');
		return;
	}
	
	$.messager.confirm("确认",
		"是否确认发布设计模版？<br/><span style='color:red'>#请确保已经过认真检查</span>",
		function (r) {
	        if (r) {
	        	$.loading(true);
	        	
	        	var url = appPath+"/itbDesignWeb/doPublish.action?ids="+ids;
	        	$.post(url,function(data){
	        		if(data=="ok"){
	        			
	        			// 缩略图2
//	        			var url2 = getImageServer()+'/tg/createDesignThumb2?designId='+ids;
//	        			$.post(url2,function(crtRet){
// 						Deleted 2017-12-12
	        			// 添加搜索信息到redis
//		        		var url3 = getApiServer()+'/v5/api4back/addDesignToRedis?ppt=0&id='+ids;
//		        		$.post(url3,function(addRet){
//		        				if(crtRet.success != 1) {
//		        					msg+='</br>*thumb2生成失败';
//		        				}
//		        				if(addRet.success != 1) {
//		        					msg+='</br>*添加redis搜索信息失败';
//		        				}
//		        				
//		        			});
	        			$.loading(false);		        				
	        			var msg='设计模版已发布!';
	        			$.messager.alert('提示信息',msg,'info');
	        			doQuery();
	        		} else {
	        			$.loading(false);
	        			$.messager.alert('提示信息','发布失败!','warning');
	        		}
	        	});
	        }
		});
}
/**
 * 取消发布
 */
function cancelPublish(){
	var selectTmpl=$("#tmplGrid").datagrid("getChecked");
	if(!selectTmpl || selectTmpl.length == 0){
		$.messager.alert('提示信息','请选择已发布设计模版进行处理！','warning');
		return;
	}else if(selectTmpl.length>1){
		$.messager.alert('提示信息','请选择单个模版进行处理！','warning');
		return;
	}
	
	var ids = "";
	var uniItemId = "";
	var doFlg = false;
	$.each(selectTmpl, function(index, item){
		if(item.publish == 1 || item.publish == '1'){
			doFlg = true;
			//ids = ids + item.design_id + ",";
			ids = item.design_id;
			uniItemId = item.uni_item_id;
		}
	});
	
	if(!doFlg){
		$.messager.alert('提示信息','请选择已发布设计模版进行处理！','warning');
		return;
	}
	
	$.messager.confirm("确认", "是否确认取消已发布设计模版？", function (r) {
		if(r){
			var url = appPath+"/itbDesignWeb/cancelPublish.action?ids="+ids+"&uniItemId="+uniItemId;
			$.post(url,function(data){
				if(data=="ok"){
					
// Deleted 2017-12-12
					// 清除搜索信息到redis
//        			var url3 = getApiServer()+'/v5/api4back/delDesignToRedis?ppt=0&id='+ids;
//        			$.post(url3,function(delRet){
//        				
        				var msg='设计模版已取消发布!';
//        				if(delRet.success != 1) {
//        					msg+='</br>*删除redis搜索信息失败';
//        				}
//        				
        				$.messager.alert('提示信息',msg,'info');
	        			doQuery();
//        			});
        			
				} else {
					$.messager.alert('提示信息','设计模版取消发布失败','info');
				}
			});
		}
	});
}


/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	
	var findTmplType =$("#queryTmplType3").combobox('getValue');
	if(!findTmplType){
		findTmplType =$("#queryTmplType2").combobox('getValue');
		if(!findTmplType){
			findTmplType=$("#queryTmplType").combobox('getValue');
		}
	}
		
	var findVip = $("#queryVip").combobox('getValue');
	var findPubFlg = $("#queryPublish").combobox('getValue');
	var findTmplName=$("#queryTmplName").val();
	var findTmplId=$("#queryTmplId").val();
	var findItemId=$("#queryItemId").val();
	
	if (findTmplType) {
		queryObject.findTmplType = findTmplType;// 类型
	}
	
	var findOrg = $("#queryTgOrg").combobox('getValue');
	
	if(findOrg&&Number(findOrg||'0')>0) queryObject.findOrg = findOrg;// 组织机构
	if(findVip&&findVip.length>0) queryObject.findVip = findVip;// vip
	if(findPubFlg&&findPubFlg.length>0) queryObject.findPubFlg = findPubFlg;// 发布标记
	if(findTmplName&&findTmplName.length>0) queryObject.findTmplName = findTmplName;// 模版名称
	if(findTmplId&&findTmplId.length>0) queryObject.findTmplId = findTmplId;// 模版id
	if(findItemId&&findItemId.length>0) queryObject.findItemId = findItemId;// 商品id
	
	return queryObject;
}

function getQueryParam2(){
	var queryObject = {
		designId: Number($("#sDId").val()||'0')
	};
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(startFlg){
	$("#tmplGrid").datagrid('unselectAll');
	if(startFlg == 1) {
		$("#tmplGrid").datagrid('load', getQueryParam());
	} else {
		$("#tmplGrid").datagrid('reload', getQueryParam());
	}
}
function doQuery2(){
	$("#saleGrid").datagrid('unselectAll');
	$("#saleGrid").datagrid('load', getQueryParam2());
}

//用户文档
function doQuery3(){
	$("#uDocGrid").datagrid('unselectAll');
	$("#uDocGrid").datagrid('load', getQueryParam3());
}

function getQueryParam3(){
	var obj = {};
	var docId = $("#queryDocId").val();
	var userId = $("#queryUserId").val();
	var mobile = $("#queryMobile").val();
	if(Number(docId)>0) obj.findDocId = docId;
	if(Number(userId)>0) obj.findUserId = userId;
	if(Number(mobile)>=0){
		obj.findMobile = mobile;
	}else{
		$.messager.alert('提示信息','请输入有效数字!','info');
	} 
	return obj;
}

function ShowViSize(sizeId,viPos){
	$("#viSizeBtn").show();
	$("#viSizeId").html(sizeId);
	$("#viSizePos").val(viPos);
	$('#viSizeInfoDlg').window({
		title:'占位图信息',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#viSizeInfoDlg').window('move',{top:20,left:20});
	$('#viSizeInfoDlg').window('open');
}

function cancelShowViSize(){
	$('#viSizeInfoDlg').window('close');
}


// 关键词窗口
function editKeyword(dId,topType){
	$("#kwDId").val(dId);
	$("#kwType").val(topType);
	$('#keywordTable').html('');
	
	var url = appPath+"/itbDesign/getKeywordLst.action?designId="+dId;
	$.post(url,function(ret){	
		if(ret && ret.length>0){
			for(var i=0; i<ret.length; i++){
				var sub = ret[i];
				if(sub && sub.length>0 && sub[0].type!=10){
					var itemHtml = '<tr><td class="queryTitle" width="80px">'+sub[0].type_name+'标签</td>'+
							'<td class="queryContent" colspan="4">';
					for(var n=0; n<sub.length; n++){
						var chk = (Number(sub[n].doc_id||'0')>0)?"checked":"";
						itemHtml += '<div style="width:80px;float:left">'+
							'<input type="checkbox" '+chk+' id="kwId_'+sub[n].key_id+'" name="keywordInfo" value="'+sub[n].key_id+'"/>'+
							sub[n].key_name+'</div>';
					}
					itemHtml += '</td></tr>';
					$('#keywordTable').append(itemHtml);
				}
			}
			
			$('#keywordTable').append('<tr><td class="queryTitle" width="80px">自定义标签</td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_1"/></td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_2"/></td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_3"/></td>'+
					'<td class="queryContent" width="60px"><input class="inputText" type="text" id="myKwName_4"/></td>'+
					'</tr>');

			for(var i=0; i<ret.length; i++){
				var sub = ret[i];
				if(sub && sub.length>0 && sub[0].type==10){
					var cnt=1;
					for(var n=0; n<sub.length; n++){
						if(cnt<=4){
							$('#myKwName_'+cnt).val(sub[n].key_name);
							cnt+=1;
						}
					}
					break;
				}
			}
		}
	});
	
	// show dlg
	$("#keywordBtn").show();
	$('#keywordDlg').window({
		title:'关键词标签设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#keywordDlg').window('move',{top:20,left:20});
	$('#keywordDlg').window('open');
}
function updKW(){
	var defKeys = $("input[name='keywordInfo']:checked").map(function(){
        	return $(this).val();
        }).get();
	
	var userKeys = [];
	for(var i=1; i<=4; i++){
		var keyNm = $('#myKwName_'+i).val();
		if(keyNm && keyNm.length>0) userKeys.push(keyNm);
	}
	
	var dId = $("#kwDId").val();
	var topType = $("#kwType").val();
	
	var url = getDesignServer()+'/encrypt/encrypt';
	var data = encryptParas({
		'type':topType,
		'uId':g_userId,
		'dId':dId,
		'defKeys': defKeys,
		'userKeys': userKeys,
		'destination': '/user/updDocKw'
		});
	$.post(url,data,function(ret){
		if(ret.success == 1){
			$.messager.alert('提示信息','关键词标签已更新！','info');
		}else{
			$.messager.alert('提示信息',(ret.msg||'更新失败'),'info');
		}
	});
}
function cancelKW(){
	$('#keywordDlg').window('close');
}

// 专题窗口
function editTopic(dId,type,parentType,topType){
	$("#stDId").val(dId);
	$("#stType").val(topType);
	$('#topicTable').html('');
	
	var typeIds = ""+type+","+parentType+","+topType;
	
	var url = appPath+"/itbDesign/getTopicInfoLst.action";
	var sendData = {
		"designId":dId,
		//"topType":topType,
		"typeIds":typeIds
	}
	$.post(url,sendData,function(ret){	
		if(ret && ret.length>0){
			for(var i=0; i<ret.length; i++){// 按use分组
				var sub = ret[i];
				if(sub && sub.length>0 && sub[0].top_type==topType){
					
					var useNm = '专题';
					if(sub[0].use==1){
						useNm = '热门';
					}
					var itemHtml = '<tr><td class="queryTitle" width="60px">'+useNm+'</td>'+
							'<td class="queryContent" colspan="4">';
					for(var n=0; n<sub.length; n++){
						var chk = (Number(sub[n].item_id||'0')>0)?"checked":"";
						itemHtml += '<div style="width:120px;float:left">'+
							'<input type="checkbox" '+chk+' id="stId_'+sub[n].key_id+'" name="topicInfo" value="'+sub[n].st_id+'"/>'+
							sub[n].title+'</div>';
					}
					itemHtml += '</td></tr>';
					$('#topicTable').append(itemHtml);
				}
			}
		}
	});
	
	// show dlg
	$("#topicBtn").show();
	$('#topicDlg').window({
		title:'热门/主题设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#topicDlg').window('move',{top:20,left:20});
	$('#topicDlg').window('open');
}
function updTopic(){
	var stIds = $("input[name='topicInfo']:checked").map(function(){
        	return $(this).val();
        }).get();//.join(',')
	
	var dId = $("#stDId").val();
	var topType = $("#stType").val();
	
	var url = getDesignServer()+'/encrypt/encrypt';
	var data = encryptParas({
		'type':topType,
		'dId':dId,
		'stIds': stIds,
		'destination': '/user/updDocTopic'
		});
	$.post(url,data,function(ret){
		if(ret.success == 1){
			$.messager.alert('提示信息','热门/专题已更新！','info');
		}else{
			$.messager.alert('提示信息',(ret.msg||'更新失败'),'info');
		}
	});
}
function cancelTopic(){
	$('#topicDlg').window('close');
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}


// 上传设计源文件
function showSrcUploadDlg(dId, url){
	$('#srcUploadForm').form('clear');
	$("#upDId").val(dId);
	$('#curSrcUrl').html(url||'无');
	
	clearUploadList();
	
	$("#srcUploadBtn").show();
	$('#srcUploadDlg').window({
		title:'上传设计源文件文件',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#srcUploadDlg').window('move',{top:20,left:20});
	$('#srcUploadDlg').window('open');

	initOSS();
}
function cancelSrcUpload(){
	$('#srcUploadDlg').window('close');
}

function clearSrcUrl() {
	$.messager.confirm("确认", "是否确认清除源文件", function (r) {  
        if (r) {
        	updSrcUrlInfo();
        }
	});
}
// 更新url
function updSrcUrlInfo(fileName, fileNameNoExt ,urlpath) {
	var designId = $("#upDId").val();
	if((Number(designId||'0')||0) <= 0) {
		$.messager.alert('提示信息','无效设计模版ID!','warning');
		return;
	}
	
	var url = appPath+"/itbDesignWeb/updDesignSrcUrl.action"
	var sendData = {
		"designId": designId,
		"srcUrl": urlpath||''
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") {
			$('#curSrcUrl').html(urlpath||'无');
			$.messager.alert('提示信息','数据更新成功','info');
			//$('#srcUploadDlg').window('close');
			doQuery();
        } else {
        	$.messager.alert('提示信息','数据更新失败','info');
        }
    });
}

//############### FOR OSS UPLOAD START ###############
var g_object_name = '';
var dtNow = Date.parse(new Date())/1000;

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
  }
	return str;
}

function getSuffix(filename) {
  var pos = filename.lastIndexOf('.');
  var suffix = '';
  if (pos != -1) {
      suffix = filename.substring(pos);
  }
  return suffix;
}

function calculate_object_name(filename) {
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
    g_object_name = "source/"+nowStr + randomString(20)+"/"+filename;
}

function set_upload_param(up, filename, ret) {
  
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date())/1000;
	OSS_PARAM.flg = false;
	if (OSS_PARAM.expire/1000 < dtNow + 5) {// 5s
	  	var url = appPath+"/itbFont/getOSSToken.action"
	      $.get(url, function(data){  
	  		if (data && data.signature) { 
	  			OSS_PARAM.expire = data.expire;
	  			OSS_PARAM.uploadHost = data.uploadHost;
	  			OSS_PARAM.accessKeyId = data.accessKeyId;
	  			OSS_PARAM.policyBase64 = data.policyBase64;
	  			OSS_PARAM.signature = data.signature;
	  			OSS_PARAM.flg = true;
	  			
	  			doUpStart(up, filename, ret);
	          } else {
	          	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
	          }  
	      }
	    );
	} else {
	  	doUpStart(up, filename, ret);
	}
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
		calculate_object_name(filename);
	}
	var new_multipart_params = {
		'key' : g_object_name,
		'policy': OSS_PARAM.policyBase64,
		'OSSAccessKeyId': OSS_PARAM.accessKeyId,
		'success_action_status' : '200', //让服务端返回200,不然默认会返回204
		'signature': OSS_PARAM.signature,
	};

	up.setOption({
		'url': OSS_PARAM.uploadHost,
		'multipart_params': new_multipart_params
	});

	up.start();
}

function clearUploadList() {
	$(".upload_progress_bar").remove();
	$(".upload_progress").remove();
	$(".upload_file_info").remove();
}

function initOSS() {
	if (uploader) {
		return;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selSrcFile', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',

		init: {
			PostInit: function() {
				document.getElementById('postFiles').onclick = function() {
		            set_upload_param(uploader, '', false);
		            return false;
				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bHasOne = false;// 一次只能上传一个
				plupload.each(files, function(file) {
					if(bHasOne || !isValidFile(file.name)) {
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					} else {
						// add file info list
						document.getElementById('ossfile').innerHTML += 
	                    	'<div id="' + file.id + '" class="upload_file_info">'
	                    	+ file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>'
	                    	+ '<div class="upload_progress">'
	                    	+ '<div class="upload_progress_bar" style="width: 0%">'
	                    	+ '</div></div></div>';
						bHasOne = true;
					}
				});
				
				if (!bHasOne) {
					setMsg("red", "已过滤无效文件！");
				}
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0];
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
				
				setMsg("green", file.name + ' 上传中...');
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功:' + g_object_name;
	            	
	            	var pos = file.name.lastIndexOf(".");
	                var fileNameNoExt = file.name.substring(0, pos);
	            	updSrcUrlInfo(file.name, fileNameNoExt, OSS_PARAM.uploadHost+'/'+ g_object_name);
	            	setMsg("green", '上传成功!');
	            }
	            else {
	            	setMsg("red", '上传出错！');
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
	            }
			},

			Error: function(up, err) {
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}

function setMsg(color, msg) {
	$('#msgTxt').css("color", color);
	$('#msgTxt').val(msg);
	$('#uploadMsg').show();
}

function isValidFile(url) {
    var res, suffix = "";
    var fontSuffixes = ["jpg","jpeg","bmp","png","tif","tiff","pdf","psd","ai","eps","cdr","tga","dwg"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = fontSuffixes.length; i < l; i++) {
        if (suffix === fontSuffixes[i]) {
            return true;
        }
    }
    return false;
}
//############### FOR OSS UPLOAD END ###############

// 查看显示 设计模板的表单情况
function showDesignForm(){
	var uni_item_id = $("#yjxUnitemId").val();
	var designId = $("#yjxDesignId").val();
	var formId = $("#yjxFormId").val();
	
	// 保存 值的情况
	$("#uitemId").val(uni_item_id);// 模板统一ID
	$("#designIdForm").html(designId);
	if (formId){
		$("#formId").html(formId);
	} else {
		$("#formId").html("暂未设置表单");
	}
	
	$('#tgFormDlg').window({
		title:'设计模板设置表单列表',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#tgFormDlg').window('move',{top:20,left:20});
	$('#tgFormDlg').window('open');
	initTgForm();
}

// 初始化 加载表单列表
function initTgForm(){
	$('#tgFormTable').datagrid({
	    url:appPath + "/yjxForm/getFormMgrInfo.action",
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    singleSelect:true,
	    collapsible: true,
		checkbox:false,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'form_id',title:'表单ID',width:25,align:'center',sortable:false}, 
	        {field:'form_type',title:'表单类型',width:35,align:'center',sortable:true,
	        	formatter:function(value,rowData,rowIndex){
	        		var ret = 'Nan';
	        		switch(value){
	        		case 10: ret = '用户收集'; break;
	        		}
	        		return '<span style="color:#B22222;">'+ret+'</span>';
	        	}
	        },
	        {field:'key1',title:'项目1',width:25,align:'center',sortable:true},
	        {field:'key2',title:'项目2',width:25,align:'center',sortable:true},
	        {field:'key3',title:'项目3',width:25,align:'center',sortable:true},
	        {field:'key4',title:'项目4',width:25,align:'center',sortable:true},
	        {field:'key5',title:'项目5',width:25,align:'center',sortable:true},
	        {field:'key6',title:'项目6',width:25,align:'center',sortable:true},
	        {field:'key7',title:'项目7',width:25,align:'center',sortable:true},
	        {field:'key8',title:'项目8',width:25,align:'center',sortable:true},
	        {field:'key9',title:'项目9',width:25,align:'center',sortable:true},
	        {field:'key10',title:'项目10',width:25,align:'center',sortable:true},
	        {field:'desc',title:'描述',width:40,align:'center',sortable:true},
	        {field:'thumb',title:'缩略图',width:40,align:'center',sortable:true},
	        {field:'create_time',title:'创建时间',width:40,align:'center',sortable:true},
	        {field:'update_time',title:'修改时间',width:60,align:'center',sortable:true}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:false,
		toolbar:[{
		 			text:'给设计模板添加表单',
		 			iconCls:'icon-ok',
		 			handler:function(){
		 				addFormId();
		 			}
		 		}],
		onLoadSuccess: function(){
			$(this).datagrid('freezeRow',0).datagrid('freezeRow',1);
		}
	});
}

// 添加formId 到统一模板表
function addFormId(){
	var selectItem=$("#tgFormTable").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择设计模版','warning');
		return;
	}
	var unItemId=$("#uitemId").val();// 模板统一ID
	if(!unItemId || unItemId.length == 0){
		$.messager.alert('提示信息','该模板有问题,请联系管理员','warning');
		return;
	}
	$.messager.confirm("确认", "是否确定给设计模板添加附加表单？", function (r) {  
        if (r) { 
        	$.loading(true);
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = item.form_id;
			});
			var url = appPath+"/itbWebVideo/addVideFormId.action?formId="+ids+"&unItemId="+unItemId;
			$.post(url,function(data){
				$.loading(false);
				if(data=="ok"){
					$.messager.alert('提示信息','添加表单成功','info');
				}else{
					$.messager.alert('提示信息','添加表单失败','info');
				}
				doQuery();
			});
        }
	});
}